<?php 


class Category{
	
	public static $msgs = array();
 		
	function __construct()
	{
 	}
	
	/* 
	***  Public Functions
	*/
		 
	function getChildCategories($data)
	{	
		global $db, $pager, $config;
		$sql = "SELECT * FROM category where status = 1 and parent_id = '".intval($data['category_id'])."' ";
		$result = $db->fetch_all($sql);
 		return $result;
	}
	
	function getCategoryById($data)
	{
		global $db;	
		$result = $db->first("SELECT * FROM category WHERE status = 1 AND category_id = ".intval($data['category_id']));
		if( $result['parent_id'] > 0 ) {
			$parent_data = $db->first("SELECT large_image FROM category WHERE status = 1 AND category_id = ".intval($result['parent_id']));	
			$result['large_image'] = $parent_data['large_image'];
		}
 		return $result;
	}
 	
	function getProductsByCategoryById($data)
	{
		global $db, $pager, $config;
		$sql = "SELECT * FROM products where status = 1 and category_id = '".intval($data['category_id'])."' ";
		$result = $db->fetch_all($sql);
 		return $result;
	}
	
	function getProductDetailById($data)
	{
		global $db, $pager, $config;
		$product_id = (int)$data['product_id'];
		$sql = "SELECT * FROM products where status = 1 and product_id = '".$product_id."' ";
		$product = $db->first($sql);
		
		if( $product['size_id'] > 0 ) {
			$product['size_dropdown'] = $this->getSizeSelect($product['size_id']);
		}
		
		$sql = "SELECT * FROM item_images WHERE type='product' AND item_id = '".$product_id."' order by id asc";
		$images = $db->fetch_all($sql);
		$product['images'] = $images;
      	return $product;
	}
	
	function getSizeSelect($size_id)
	{
		global $db;
		$sql = "SELECT size_values FROM sizes WHERE size_id = '".$size_id."' ";
		$sizes = $db->first($sql);
		$sizes = $sizes['size_values'];
		
		$size_arr = explode('~', $sizes);
		$html = "<select name='size' id='size'><option value=''>size</option>";
		foreach($size_arr as $val)
		{
			$html .= "<option value='{$val}'>{$val}</option>";	
		}
		$html .= "</select>";
		return $html;
	}
	
	function getProductById($data)
	{
		global $db;	
		$sql = "SELECT * FROM products where status = 1 and product_id = '".$data['product_id']."' ";
		return $db->first($sql);
	}
	
	function addToCart($data)
	{
		global $db;
		$session_id = session_id();
		$product_data = $this->getProductById($data);
 		$sql = "delete from temp_cart where session_id = '{$session_id}' and product_id = '{$data[product_id]}'";
		$db->query($sql);
 		$record = array(
			 				 'session_id' => $session_id,	
							 'product_id' => $data['product_id'],	
						  	 'size' => $data['size'],
							 'color' => $product_data['color'],
							 'quantity' => $data['quantity'],
 							 'price' => $product_data['price'], 
						  	 'created_on' => date('Y-m-d H:i:s')
					       );
		
		$db->insert("temp_cart", $record);
		redirect("cart.php?updated=1");
	}
	
	function getCartContents()
	{
		global $db;
		$session_id = session_id();
		$sql = "SELECT p.*, tc.quantity, tc.color, tc.size, (tc.quantity*p.price) as sub_total
					FROM temp_cart tc
					INNER JOIN products p ON (tc.product_id = p.product_id)
				WHERE
					session_id = '{$session_id}'
					";
		
		$result = $db->fetch_all($sql);
       	return $result;
	}
	
	function updateCart($data)
	{
		global $db;
		$session_id = session_id();
		
		$quantity_arr = $data['quantity'];
		$product_id_arr = $data['product_id'];
		
		$total = count($data['quantity']);
		
		for($i=0; $i < $total; $i++)
		{
			$record = array(
			 				 'quantity' => $quantity_arr[$i], 
						  	 'created_on' => date('Y-m-d H:i:s')
					       );
		
			
			
			$where = array( "session_id" => $session_id, 'product_id' => $product_id_arr[$i]);	
			$db->update("temp_cart", $record, $where);
			
		}
		redirect("cart.php?updated=1");
	}
	
	function removeProductFromCart($data)
	{
		global $db;
		$session_id = session_id();
		$product_id = $data['product_id'];
		
		$sql = "delete from temp_cart where session_id = '{$session_id}' and product_id = '{$data[product_id]}'";
		$db->query($sql);
		redirect("cart.php?updated=1");
	}
	
	function saveOrder($data)
	{
		global $db;
		$session_id = session_id();
		
 		$record = array(
			 				 'name' => $data['name'],	
							 'email' => $data['email'],
							 'company' => $data['company'],
							 'phone_number' => $data['phone_number'],
							 'message' => $data['message'],
							 'contact' => $data['contact'],
 						  	 'created_on' => date('Y-m-d H:i:s')
					       );
		
		$user_id = $db->insert("users", $record);
		
		
		$sql = "SELECT * FROM temp_cart  WHERE session_id = '{$session_id}'";
		$cartdata = $db->fetch_all($sql);
		$datetime = date('Y-m-d H:i:s');
		if( count($cartdata) > 0 ) 
		{
			foreach( $cartdata as $row)
			{
				$record = array(
								 'user_id' => $user_id,	
								 'product_id' => $row['product_id'],
								 'price' => $row['price'],
								 'quantity' => $row['quantity'],
								 'size' => $row['size'],
								 'color' => $row['color'],
								 'created_on' => $datetime
							   );
			
				$db->insert("orders", $record);
			}
			
			$data['user_id'] = $user_id;
			if( $this->sendOrderEmail($data) )
			{
				$sql = "delete from temp_cart where session_id = '{$session_id}' ";
				$db->query($sql);	
				redirect('cart.php?action=order_form&success=1');  
			}
			else
			{
				redirect('cart.php?action=order_form&error=1');		
			}
		}
		else
		{
			redirect('cart.php?action=order_form&error=1');	
		}
 	}
	
	function sendOrderEmail($data)
	{
		global $db, $config;
		$user_id = $data['user_id'];
		$sql = "SELECT p.name, o.price, o.quantity, (o.price*o.quantity) as sub_total, o.size, o.color FROM orders o INNER JOIN products p ON o.product_id = p.product_id WHERE o.user_id = '{$user_id}'";
		$order_data = $db->fetch_all($sql);
 		if( count($order_data) > 0 ) 
		{
 			$html = "<div><table>
					<tr> <td> Name : $data[name] </td> </tr>
					<tr> <td> Email : $data[email] </td> </tr>
					<tr> <td> Company : $data[company] </td> </tr>
					<tr> <td> Contact : $data[contact]</td> </tr>
					<tr> <td> Phone Number : $data[phone_number] </td> </tr>
				</table><div><br>";
 		
			$html .= "<div><h2> Order Detail</h2><br><table cellpadding='4' cellpadding='4' border='1' style='border-collapse:collapse'>";
					
			$html .= "<tr><td>Product</td><td> Size </td> <td> Color </td> <td> Unit Price </td> <td> Quantity </td> <td align='right'> Total </td></tr>";
			
			$grand_total = 0;
			foreach( $order_data as $row)
			{
				$grand_total += $row['sub_total'];
				$html .= "<tr>
							<td>{$row[name]}</td>
							<td>{$row[size]}</td>
							<td>{$row[color]}</td>
							<td>{$row[price]}</td>
							<td>{$row[quantity]}</td>
							<td align='right'>{$row[sub_total]}</td>
						</tr>";
			}
			
			$html .= "<tr><td colspan='5'>Grand Total<td align='right'> <strong>{$grand_total}</strong> </td></tr>";
			
			
			$html .= "</table></div>";	
			
			
			$html .= "<br /><br /> {$config[from_name]}<br>{$config[from_email]}<br />";
			
 			$subject = $config['sitename'].'::Order Detail -'.date('m-d-Y H:i:s');
			
			$headers  = 'MIME-Version: 1.0' . "\r\n";
			$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
 			// Additional headers
			$headers .= 'To: '.$data['name'].' <'.$data['email'].'>' . "\r\n";
			$headers .= 'From: '.$config['from_name'].' <'.$config['from_email'].'>' . "\r\n";
			$headers .= 'Cc: '.$config['admin_email'].'' . "\r\n";
			//$headers .= 'Bcc: birthdaycheck@example.com' . "\r\n";
			
			$to = $data['email'];
			// Mail it
			return mail($to, $subject, $html, $headers);
			
			
		}
		
	}
	
	function sendContactUs($data)
	{
		global $db, $config;
 		$html = "<div><table cellpadding='4' cellpadding='4' border='1' width='90%' style='border-collapse:collapse'>
					<tr> <td align='left' nowrap='nowrap'> Name : $data[name] </td> </tr>
					<tr> <td align='left' nowrap='nowrap'> Email : $data[email] </td> </tr>
					<tr> <td align='left' nowrap='nowrap'> Company Name : $data[company_name] </td> </tr>
					<tr> <td align='left' nowrap='nowrap'> Phone # : $data[phone_no] </td> </tr>
					<tr> <td align='left' nowrap='nowrap'> Mobile # : $data[mobile_no] </td> </tr>
					<tr> <td align='left'> Message : $data[message] </td> </tr>
 				</table><div>";
 
 			$html .= "<br /><br /> {$config[from_name]}<br>{$config[from_email]}<br />";
			
 			$subject = $config['sitename'].':: Contact Us Request ';
			
			$headers  = 'MIME-Version: 1.0' . "\r\n";
			$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
 			// Additional headers
			$headers .= 'To: MikeTyson <'.$config['admin_email'].'>' . "\r\n";
			$headers .= 'From: '.$$data['name'].' <'.$data['email'].'>' . "\r\n";
			$headers .= 'Cc: hillandhill.sports@gmail.com' . "\r\n";
			//$headers .= 'Bcc: birthdaycheck@example.com' . "\r\n";
			
			$to = $config['admin_email'];
			// Mail it
			$res =  mail($to, $subject, $html, $headers);	
			if( $res ) {
				redirect("contact-us.php?success=1");
			} else {
				redirect("contact-us.php?error=1");	
			}
	}
	
	function getGalleryImages()
	{
		global $db, $pager, $config;
		$pager = new Paginator();

		
		//$config['page_limit'] =	( intval($data['new_page_limit']) > 0 ) ? $data['new_page_limit'] : $config['page_limit'];
		$page_limit = 16; 
		if(isset($_GET['pg'])&& $_GET['pg'] > 0 ){ 
			$limit_lenght  = (($_GET['pg']-1)*$page_limit) ; 
			$limit = "limit $limit_lenght, $page_limit ";
		}else{
			$limit = "limit 0 , $page_limit ";
			if($data['new_page_limit'] == 'all') 
				$limit = '';
		}
		
	/*	for($i = 1; $i<=165; $i++) {
		$image = "$i.jpg";	
		$record = array(
			 				 'large_image' => $image,	
							 'thumb_image' => $image
					       );
		
			$db->insert("photos", $record);	
			
		}*/
		
		/*require_once($config['basedir'].'/include/classes/image.class.php');
		$im = new Image;
		
		for($i = 1; $i<=44; $i++) {
		
		$image = "$i.jpg";
		$path = $config['basedir'].'/images/gallery/thumb/'.$image;
		
		//$im->copyImage($source_file, $thumb_gallery_photo);		// copy thumb_gallery_photo image and resize it
		if ( $im->loadFile($path) )
		{
			$im->resizeMaxSize(150);
			$im->build(); 	
		}
			
			
			$record = array(
			 				 'large_image' => $image,	
							 'thumb_image' => $image
					       );
		
			$db->insert("photos", $record);	
		}*/
		

		$sql = "SELECT SQL_CALC_FOUND_ROWS * FROM photos order by ordering $limit ";
		$result = $db->fetch_all($sql);
 		$counter = $db->queryCount();
		$pager->items_total = $counter[0];
		$pager->default_ipp = $page_limit;
		$pager->paginate($path);
  		return $result;	
		
	}
	
}


?>